package com.metaverse.backend.security;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.metaverse.backend.domain.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.ZoneId;
import java.util.Collection;
import java.util.Date;

/**
 * Created by stephan on 20.03.16.
 */
public class JwtUser implements UserDetails {

    private static final long serialVersionUID = 5803985158027956021L;

    private final Collection<? extends GrantedAuthority> authorities;
    private final Date                                   lastPasswordResetDate;
    private       User                                   user;


    public JwtUser(User user, Collection<? extends GrantedAuthority> authorities) {
        this.authorities = authorities;
        this.lastPasswordResetDate = Date.from(user.getCreatedAt().atZone(ZoneId.systemDefault()).toInstant());
        this.user = user;
    }

    @JsonIgnore
    public Long getId() {
        return user.getId();
    }

    @Override
    public String getUsername() {
        return user.getUsername();
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @JsonIgnore
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @JsonIgnore
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public boolean isEnabled() {
        return !user.isDel();
    }

    @JsonIgnore
    public Date getLastPasswordResetDate() {
        return lastPasswordResetDate;
    }

    public User getUser() {
        return user;
    }


    public boolean isAdmin(){
        return getUser().isAdmin();
    }

}
